package com.baizhi.cmfz.realm;

import com.baizhi.cmfz.dao.UserDao;
import com.baizhi.cmfz.entity.User;
import com.baizhi.cmfz.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AuthorRealm extends AuthorizingRealm {
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserService userService;

    /**
     * 获取授权数据
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
       //1.获取用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        //2.通过用户名查询授权数据
        //获取该用户所拥有的权限
        Set<String> permissions = userService.selectResource(username);
        //获取该用户所属的角色
        Set<String> roles = userService.selectRelo(username);
        System.out.println(roles+"角色");
        System.out.println(permissions+"权限");
        //3.封装info
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //角色
        info.setRoles(roles);
        //权限
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 获取认证数据
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //1.获取用户名
        UsernamePasswordToken token1=(UsernamePasswordToken)token;
        String username = token1.getUsername();
        //2.查询数据库
        User user = userDao.loginUser(username);
        //封装info
        if (user != null) {
            return new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),this.getName());
        }

        return null;
    }
}
